package com.zcs.app.lucky.data

import cn.sxw.android.base.utils.MMKVUtils
import com.alibaba.fastjson.JSON
import com.zcs.app.lucky.entity.PrizeEntity
import com.zcs.app.lucky.isJsonList


object PrizeDataCache {
    private const val KEY_PRIZE_LIST = "KEY_PRIZE_LIST"

    private lateinit var list: MutableList<PrizeEntity>

    fun loadAllPrizes(): MutableList<PrizeEntity> {
        val json = MMKVUtils.getString(KEY_PRIZE_LIST)
        list = if (json.isJsonList()) {
            JSON.parseArray(json, PrizeEntity::class.java) as ArrayList<PrizeEntity>
        } else {
            ArrayList()
        }
        // 根据等级ID排序
        list.sortWith { p1, p2 ->
            p1.level!!.id.compareTo(p2.level!!.id)
        }
        return list
    }

    fun addPrize(prize: PrizeEntity, isModify: Boolean = false) {
        // 1.如果是修改，先移除上一个
        if (isModify) {
            removeById(prize.id)
        }
        // 在首部添加
        list.add(0, prize)
        notifyPrize()
    }

    private fun notifyPrize() {
        MMKVUtils.put(KEY_PRIZE_LIST, JSON.toJSONString(list))
    }

    fun findById(id: String): PrizeEntity {
        for (prize in list) {
            if (prize.id == id) {
                return prize
            }
        }
        return PrizeEntity()
    }

    fun removeById(id: String, notify: Boolean = false) {
        for (g in list) {
            if (g.id == id) {
                list.remove(g)
                break
            }
        }
        if (notify) notifyPrize()
    }
}
